package search;

import java.util.Arrays;

public class FibonacciSearch {
    //定义一个maxSize表示数列的个数
    private static int maxSize = 20;
    public static void main(String[] args) {

    }


    /**
     * 构造斐波那契数列
     * @return
     */
    public static int[] fib() {
        int[] f = new int[maxSize];
        f[0] = 1;
        f[1] = 1;
        for (int i = 2; i < f.length; i++) {
            f[i] = f[i - 1] + f[i - 2];
        }
        return f;
    }

    /**
     * 斐波那契算法
     * @param arr 数组
     * @param key 查找的值
     * @return
     */
    public static int fibonacciSearch(int[] arr,int key) {
        int low = 0;
        int high = arr.length - 1;
        int mid = 0; //这个是第三下标
        int k = 0;//斐波那契的下标代替
        int[] f = fib();
        //这三步是让斐波契那数列>arr的length，并让斐波契那的长度变成arr的长度
        while (arr.length > f[k]) {
            k++;
        }
        int[] temp = Arrays.copyOf(arr, f[k]);
        if (f[k] > arr.length) {
            for (int i = high+1; i < temp.length; i++) {
                temp[i] = temp[high];
            }
        }
        //开始查找
        while (low <= high) {
            mid = low + f[k - 1] - 1;//公式，定义mid
            if (key > temp[mid]) {
                low = mid + 1;
                k -= 2;//如果-1必错，因为f(k)必然越界
            } else if (key < temp[mid]) {
                high = mid - 1;
                k--;
            } else {
                if (mid > high) {
                    return high;
                }
                return mid;
            }
        }
        return -1;
    }
}
